package com.jirefox.loner.runtime.initialize;

import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.jirefox.loner.runtime.model.DataSourceProperties;
import com.jirefox.loner.runtime.model.DriverGroup;
import com.jirefox.loner.runtime.service.JdbcDriverService;
import com.jirefox.loner.runtime.service.SqlHolder;

@ConfigurationProperties
@Configuration
public class DataSourceConfig {

	private List<DataSourceProperties> datasources;

	public void setDatasources(List<DataSourceProperties> datasources) {
		this.datasources = datasources;
	}

	@Bean
	public SqlHolder sqlHolder(JdbcDriverService jdbcDriverService) {
		SqlHolder sqlHolder = new SqlHolder();
		ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
		for (DataSourceProperties dataSourcePropertie : datasources) {
			String name = dataSourcePropertie.getName();
			String driverGroupName = dataSourcePropertie.getDriverGroup();
			if (driverGroupName == null) {
				driverGroupName = "default";
			}
			DriverGroup driverGroup = jdbcDriverService.getDriverGroup(driverGroupName);
			Thread.currentThread().setContextClassLoader(driverGroup.getClassLoader());
			org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(
					dataSourcePropertie);
			dataSource.testIdle();
			sqlHolder.addDataSource(name, dataSource);
		}
		Thread.currentThread().setContextClassLoader(oldClassLoader);
		return sqlHolder;
	}

}
